package com.atguigu.springcloud.utils;

import com.alibaba.fastjson.JSON;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaolong
 * @version 1.0
 * @description: 文件操作类
 * @date 2021/9/30 15:02
 */
public class FileUtils {

    private final static Map<String, Object> cahe = new HashMap<>();

    private final static List<File> list = new ArrayList<>();


    /**
     * @param file json文件
     * @return jsonObject   实体对象
     * @description: 刷新文件
     */
    public static void flushJson(File file, Object jsonObject) {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(file);
            fos.write(JSON.toJSONBytes(jsonObject));
            //存入map内存当中，下次查询文件直接查内存，不用进行IO操作
            cahe.put(file.getPath(), jsonObject);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(fos);
        }
    }


    /**
     * @param file  json文件
     * @param clazz 返回实体封装对象
     * @return
     * @description: 获取本地json
     */
    public static <T> T getLocalJson(File file, Class<T> clazz) {
        T obj = (T) cahe.get(file.getPath());
        //如果不为空说明，之前刷新文件时就存在内存map当中，直接返回对象；
        if (obj != null) {
            return obj;
        }
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            //转为object对象
            obj = JSON.parseObject(in, clazz);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(in);
        }
        return obj;
    }


    /**
     * @param dir  目录
     * @param name 文件名
     * @return
     * @description: 保存文件
     */
    public static String createFileOfByte(byte[] bytes, String dir, String name) throws Exception {
        FileOutputStream fos = null;
        //判断目录是否存在
        if (mkdir(dir)) {
            String fullPath = dir + name;
            try {
                fos = new FileOutputStream(fullPath);
                fos.write(bytes);
                fos.flush();
                return fullPath;
            } finally {
                close(fos);
            }
        }
        return null;
    }


    /**
     * @param bytes    数据字节
     * @param fullPath 文件路径
     * @return
     * @description: 保存文件
     */
    public static String createFileOfByte(byte[] bytes, String fullPath) throws Exception {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fullPath);
            fos.write(bytes);
            //强制写入
            fos.flush();
            return fullPath;
        } finally {
            close(fos);
        }
    }


    /**
     * @param
     * @return
     * @description: 文件复制
     */
    public static void copyfile(File src, File desc) {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream(src);
            fos = new FileOutputStream(desc);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            close(fos, fis);
        }
    }


    /**
     * @param dir 文件目录
     * @return
     * @description: 创建目录
     */
    public static boolean mkdir(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            return file.mkdir();
        }
        return true;
    }


    /**
     * @param path 文件路径
     * @return
     * @description: 删除文件
     */
    public static boolean deleteFile(String path) {
        File file = new File(path);
        //获取父目录
        File parentFile = file.getParentFile();
        file.delete();
        //如果父目录下没有文件，删除目录
        if (parentFile.list().length == 0) {
            return deleteFile(parentFile.getPath());
        }
        return true;
    }


    /**
     * @param dir
     * @return
     * @description: 递归删除目录下的所有文件及子目录下所有的文件
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] list = dir.list();
            //递归删除目录中的子目录下
            for (int i = 0; i < list.length; i++) {
                boolean success = deleteDir(new File(dir, list[i]));
                if (!success) {
                    return false;
                }
            }
        }
        System.out.println("删除文件：" + dir.getPath());
        return dir.delete();
    }


    /**
     * @param path 目录
     * @return List<File> 所有的文件
     * @description: 获取目录下所有的文件
     */
    public static List<File> getAllFile(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                getAllFile(file1.getPath());
            }
            list.add(file1);
        }
        return list;
    }


    /**
     * @param args
     * @return
     * @description: 关闭流
     */
    public static void close(Closeable... args) {
        for (Closeable closeable : args) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    //测试
    public static void main(String[] args) {
        String path = "D:\\dirA";
        List<File> allFile = getAllFile(path);
        for (int i = 0; i < allFile.size(); i++) {
            System.out.println(allFile.get(i));
        }
    }
}
